define([
    "jquery",
    "echarts",
    'migrate_jqprint',
    'jqprint',
    "bbcare",
    "as/app/mabc/mabcDetail.ui",
    "as/app/mabc/mabcDetail.servers",
    "as/app/mabc/mabcDetailInfo.servers"
],function(jquery,echarts,migrate,$print,$bb,$ui,$servers, $infoServers){
    var event = {};
    event.init = function(info){
 		$(".panel-title.goBack").bind("click",function(){
 			$bb.openPage("mabcList",{params:info});
		})
    };
    //基础问卷的回调函数：
    event.mabcBaseInfo = function(data,params){
    	$ui.infoInit({"id":"#mabcDetailInfo","data":data.data});
    };
    /**
     * 问卷列表的回调函数
     * @param {*} data 
     * @param {*} params 
     */
    event.mabcQuestionList = function(data,params){
		$ui.questListInit({"id":"#mabcQuestList","data":data.questionList}, params);
		$(".mabcDetailBtn").on("click",function(){
			params.answerId = $(this).attr("answerId");
			params.busiId = $(this).attr("busiId");
			params.busiName = $.trim($(this).prev().text());
 			$bb.openPage("mabcDetailInfo",{params:params});
        })
        judgeIs7yearsBaseInfo(data.questionList, params)
    };

    /**
     * 如果是 7 岁问卷 则再次获取其基本信息并渲染到顶部（临时补救）
     * @param {*} list 
     * @param {*} params 
     */
    function judgeIs7yearsBaseInfo(list, params) {
        if (Object.prototype.toString.call(list) !== '[object Array]') return
        var userId = params.userId, answerId = null
        for (var i = 0; i < list.length; i++) {
            if (list[i].busiId === "mabc700001" && list[i].busiName === '基本资料') {
                answerId = list[i].answerId
            }
        }
        if (!answerId) return
        var params = {
            userId: userId,
            answerId: answerId
        }
        $infoServers.answerList(params, answerListCallback)
    } 

    var answerListCallback = function (res) {
        var answerList
        try {
            answerList = res.data.answerResult[0].questions
        } catch (err) {
            answerList = null
        }
        if (!answerList) return
        var wrap = document.getElementById('mabcDetailInfo')
        var classAge = ''
        for (var i = 0; i < answerList.length; i++) {
            if (answerList[i].name === '孩子所在年级') {
                for (var j = 0; j < answerList[i].answer.length; j++) {
                    if (answerList[i].answer[j].checked) {
                        classAge = answerList[i].answer[j].name.split('.')[1]
                    }
                }
            }
        }
        $('.class').text(classAge)
    }

    var saveScoreCallback = function(data,params){
        if(data.success){
            var inParams = {
                userId:params.userId,
                type:params.type
            };
            $servers.getmabcScore(inParams,event.getmabcScoreCallback,params);
        }else{
            $bb.toastShow(data.msg,1500);
        }
    };
    //运动表现点击事件函数：
    var  performanceClick = function(){
        if(!$(this).hasClass('grey')){
            var color = $(this).css("background-color"),item = $(this).attr("item");
            var info = $(this).data("info");
            var params = {"ps":{}};
            params.type=info.type;
            params.userId = info.userId;
            params.ps.days = info.days;
            params.ps.color = color;
            params.ps.item = item;
            params.ps.posture = $("#posture").val();
            params.ps.birthday = info.birthday;
            params.ps.pregnancDay = info.pregnancDay;
            $servers.saveScore(params,saveScoreCallback,info);
        }
    };
    //图表：
    //虚拟数据：
    var diotArr = function(){
        var arr = [];
        var min = 185.5,y1 = 6.48,max = 315;
        var num  = 7,i=0,j= 0,k= 1;
        do{
            var y = num*i;
            i++;
            arr.push([(min+y),y1]);
        }while((min+y)<max);

        var min2 = 339.5,y2= 3.48,max2 = 430;
        do{
            var y = num*j;
            j++;
            arr.push([(min2+y),y2]);
        }while((min2+y)<max2);

        var c= 0.5;
        do{
            var y = c*k;
            k++;
            arr.push([325.5,y]);
            arr.push([332.5,y]);
        }while((c+y)<7);
        return arr;
    }
    
    event.charts = function(obj){
        var arr = diotArr();
        var myChart = echarts.init(document.getElementById('chart'));
        var option = {
            tooltip: {
                trigger: 'item',
                formatter:function(params, ticket, callback){
                    var val='';
                    if(params.seriesType == "scatter" && params.seriesName == "baby"){
                        var name =JSON.parse(params.data.name);
                        var age = "";
                        var getAge = function(days,pregnancDay,birthday){
                            var age ;
                            if(birthday){
                                age = parseInt((days-pregnancDay)/7) + "周" + (days-pregnancDay)%7 + "天";
                            }else{
                                age = parseInt(pregnancDay/7) + "周" + pregnancDay%7 + "天";
                            }
                            return age
                        };
                        age = getAge(name.days*1,name.pregnancDay*1,name.birthday);
                        val += '出生周龄：'+ age + "<br/>"+'记录体位：'+ name.posture + "<br/>"+'运动表现：'+ name.evaRes + "<br/>"+'评估日期：'+ name.testTime
                    }
                    return val;
                }
            },
            grid: {
                left: '0',
                right: '20',
                bottom: '15',
                top:'10',
                width:'750',
                height:'320',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                min:'182',
                max:"434",
                interval:7,
                name:"周",
                nameLocation:"middle",
                nameGap:"24",
                boundaryGap: false,
                axisLabel: {
                    formatter: function(value,index){
                        if(value % 7 == 0){
                            if(value > 280){
                                return parseInt((value-280) / 7)
                            }else{
                                return parseInt(value / 7)
                            }
                        }
                    }
                },
                splitArea : {
                    show : false
                }
            },
            yAxis:  {
                type: 'value',
                name:"",
                nameLocation:"middle",
                nameGap:"27",
                boundaryGap: false,
                min:0,
                max:7,
                interval:1,
                axisLabel: {
                    textStyle: {
                        color: function (value, index) {
                            var color = ["","#AACA57","#70C6C9","#FACE64","#ED9772","#EF7255","#8B549B","#3B6FB3"];
                            return color[value]
                        }
                    },
                    formatter: function(value,index){
                        var label = ["","N","H","PR","Ch","CS","AF","F-"];
                        return label[index]
                    },
                    fontWeight:"bolder",
                    fontSize:"16"
                },
                splitArea : {
                    show : false
                }
            },
            series: [
                {
                    name: 'bg',
                    type: 'scatter',
                    symbol: 'rect',
                    symbolSize: function(value,number){
                        return [19.5,42]
                    },
                    data:arr,
                    itemStyle: {
                        normal: {
                            color: '#EBEBEB'
                        },
                        emphasis:{
                            color: '#EBEBEB'
                        }
                    },
                    animation:false
                },
                {
                    name:'baby',
                    type:'scatter',
                    symbolSize:"12",
                    data:obj.data
                }
            ]
        };
        myChart.setOption(option);
        $("#printImage").html('<img src="' + myChart.getDataURL({type: "png",backgroundColor: '#fff'}) + '" style="width: 100%;height:100%; "/>');

      /*  myChart.on('click', function (params) {
            console.log(params);
        });*/
    };
    //保存指导建议回调：
    var saveGuidesCallback = function(data,params){
        if(data.success){
            $bb.toastShow("保存成功",1500);
            event.getGuides(params);
        }else{
            $bb.toastShow(data.msg,1500);
        }
    };
    //获取指导意见：
    var getGuidesCallback = function(data,params){
        var guides = data.data.getGuide;
        var nowDate = $servers.getNowFormatDate();
        var nowGuides;
        //guides.length = guides.length;
        for(var i = 0;i<guides.length;i++){
            guides[i].testDate = guides[i].createTime.substring(0,10);
            if(nowDate == guides[i].testDate ){
                nowGuides = guides[i];
                $("#todayGuide").addClass("checked");
                $("#todayGuide").attr("guide",nowGuides.guide);
                var gu = nowGuides.guide ? nowGuides.guide:"暂无指导意见";
                $("#check-guide").html('<div class="item">指导建议：</div><div class="item-result">'+gu+'</div>');
                var h = '<textarea name="guides" class="form-control">'+ nowGuides.guide +'</textarea>'+
                    '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
                $("#guides_bottom").html(h);
                /* begin 南方医院 新增备注 wmp */
                $("#todayRemark").addClass("checked");
                $("#todayRemark").attr("remark",nowGuides.remark);
                var remark = nowGuides.remark ? nowGuides.remark:"";
                var h2 = '<textarea name="remark" class="form-control">'+ remark +'</textarea>'+
                    '<button class="btn btn-primary pull-right" id="toRemarkSave">保存</button>';
                $("#remark_bottom").html(h2);
                /* end 南方医院 */
            }
        }
        if(!nowGuides){
            $("#check-guide").html('<div class="item">指导建议：</div><div class="item-result"></div>');
            var h = '<textarea name="guides" class="form-control"></textarea>'+
                '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
            $("#guides_bottom").html(h);
            /* begin 南方医院 新增备注 wmp */
            var h2 = '<textarea name="remark" class="form-control"></textarea>'+
                '<button class="btn btn-primary pull-right" id="toRemarkSave">保存</button>';
            $("#remark_bottom").html(h2);
            /* end 南方医院 */
        }
        if(params.flag == 1){
            $ui.guideHideListInit({"id":"#hideList","data":guides});
            $ui.guideHideListInit({"id":"#hideRemarkList","data":guides});
        }else{
            $ui.guideListInit({"id":"#guideList","data":guides,"length":guides.length});
            $ui.guideListInit({"id":"#remarkList","data":guides,"length":guides.length});
        }

        $(".guides_top span.guide-tab").data("info",params);
        $(".guides_top").on("click","span.guide-label",event.guideListFn);
        $(".guides_top").on("click","span.guide-hide-label",event.guideListFn);
        $(".remark_top span.guide-tab").data("info",params);
        $(".remark_top").on("click","span.guide-label",event.remarkListFn);
        $(".remark_top").on("click","span.guide-hide-label",event.remarkListFn);
    };
    event.getGuides = function(params){
        $servers.getGuides(params,getGuidesCallback,params);
    };

    event.guideListFn = function(){
        if(!$(this).hasClass('guide-tab')){
            $(this).parents(".guides_top").find(".guide-label").removeClass("checked");
            $(this).addClass('checked');
            var guide = $(this).attr("guide") ? $(this).attr("guide"):'' ;
            if($(this).hasClass('todayGuide')){
                var h = '<textarea name="guides" class="form-control">'+ guide +'</textarea>'+
                    '<button class="btn btn-primary pull-right" id="toSave">保存</button>';
            }else{
                h = '<textarea name="guides" class="form-control"  disabled>'+guide+'</textarea>';
            }
            $("#guides_bottom").html(h);
        }
    };
    event.remarkListFn = function(){
        if(!$(this).hasClass('guide-tab')){
            $(this).parents(".remark_top").find(".guide-label").removeClass("checked");
            $(this).addClass('checked');
            var remark = $(this).attr("remark") ? $(this).attr("remark"):'' ;
            if($(this).hasClass('todayRemark')){
                var h = '<textarea name="guides" class="form-control">'+ remark +'</textarea>'+
                    '<button class="btn btn-primary pull-right" id="toRemarkSave">保存</button>';
            }else{
                h = '<textarea name="guides" class="form-control"  disabled>'+remark+'</textarea>';
            }
            $("#remark_bottom").html(h);
        }
    };
    var guideTabFn = function(){
        if($(this).attr("show")){
            $(this).parents(".guides").find(".hideList").css("display","none");
            $(this).removeAttr("show");
        }else{
            var info = $(this).data("info");
            $(this).parents(".guides").find(".hideList").css("display","block");
            $(this).attr("show",true);
            var params = $.extend({},info,{});
            params.flag = 1;
            event.getGuides(params);
        }
    };
    //打印函数：
    event.printReport = function(){
        var params = $(this).data("params");
        var $pc=$(params.dom);
        $pc.jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
    };
    return event;
});